package com.ruoyi.basic.service.impl;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.constant.BasicConstants;
import com.ruoyi.basic.domain.BasicEducate;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.mapper.BasicUserMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.basic.mapper.BasicPositionalMapper;
import com.ruoyi.basic.domain.BasicPositional;
import com.ruoyi.basic.service.IBasicPositionalService;
import com.ruoyi.common.core.text.Convert;

/**
 * 职称聘任Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-12-23
 */
@Service
public class BasicPositionalServiceImpl extends ServiceImpl<BasicPositionalMapper, BasicPositional> implements IBasicPositionalService
{

    @Autowired
    private BasicUserMapper userMapper;

    /**
     * 查询职称聘任
     * 
     * @param positionalId 职称聘任主键
     * @return 职称聘任
     */
    @Override
    public BasicPositional selectBasicPositionalByPositionalId(Long positionalId)
    {
        return baseMapper.selectBasicPositionalByPositionalId(positionalId);
    }

    /**
     * 查询职称聘任
     *
     * @param positionalIds 职称聘任主键
     * @return 职称聘任
     */
    @Override
    public List<BasicPositional> selectBasicPositionalByPositionalIds(String positionalIds)
    {
        LambdaQueryWrapper<BasicPositional> queryWrapper = new LambdaQueryWrapper<BasicPositional>();
        queryWrapper.in(BasicPositional::getPositionalId, Convert.toLongArray(positionalIds));
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 查询职称聘任列表
     * 
     * @param basicPositional 职称聘任
     * @return 职称聘任
     */
    @Override
    public List<BasicPositional> selectBasicPositionalList(BasicPositional basicPositional)
    {
        return baseMapper.selectBasicPositionalList(basicPositional);
    }

    /**
     * 新增职称聘任
     * 
     * @param basicPositional 职称聘任
     * @return 结果
     */
    @Override
    public int insertBasicPositional(BasicPositional basicPositional)
    {
        basicPositional.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(basicPositional);
    }

    /**
     * 修改职称聘任
     * 
     * @param basicPositional 职称聘任
     * @return 结果
     */
    @Override
    public int updateBasicPositional(BasicPositional basicPositional)
    {
        basicPositional.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(basicPositional);
    }

    /**
     * 批量删除职称聘任
     * 
     * @param positionalIds 需要删除的职称聘任主键
     * @return 结果
     */
    @Override
    public int deleteBasicPositionalByPositionalIds(String positionalIds)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(positionalIds)));
    }

    /**
     * 删除职称聘任信息
     * 
     * @param positionalId 职称聘任主键
     * @return 结果
     */
    @Override
    public int deleteBasicPositionalByPositionalId(Long positionalId)
    {
        return baseMapper.deleteById(positionalId);
    }

    /**
     * 导入职称聘任
     *
     * @param positionalList 职称聘任列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importPositional(List<BasicPositional> positionalList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(positionalList) || positionalList.size() == 0)
        {
            throw new ServiceException("导入员工职称聘任数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        String REGEX_LOCALE_ENGLISH = "^[a-zA-Z]{3}\\s[a-zA-Z]{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s[A-Z]{3}\\s\\d{4}$";
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BasicPositional positional : positionalList)
        {
            try
            {
                if(StringUtils.isEmpty(positional.getPositionalType())){
                    continue;
                }
                //获取用户信息
                BasicUser user = userMapper.selectOne(new LambdaQueryWrapper<BasicUser>()
                        .eq(BasicUser::getIdCard, positional.getIdCard()).last("limit 1"));
                if(StringUtils.isNotNull(user)) {
                    positional.setUserId(user.getId());
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，员工 " + positional.getUserName() + " 不存在");
                    continue;
                }

                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

                if(positional.getObtainTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date obtainTime = dateFormat.parse(positional.getObtainTime());
                    positional.setObtainTime(DateUtils.parseDateToStr("yyyy-MM-dd", obtainTime));
                }
                if(positional.getEngageTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date engageTime = dateFormat.parse(positional.getEngageTime());
                    positional.setEngageTime(DateUtils.parseDateToStr("yyyy-MM-dd", engageTime));
                }

                BasicPositional p = baseMapper.selectOne(new LambdaQueryWrapper<BasicPositional>()
                        .eq(BasicPositional::getPositionalType, positional.getPositionalType())
                        .eq(BasicPositional::getObtainTime, positional.getObtainTime())
                        .eq(BasicPositional::getUserId, positional.getUserId()).last("limit 1"));
                if (StringUtils.isNull(p))
                {
                    positional.setCreateBy(operName);
                    this.insertBasicPositional(positional);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、员工 " + positional.getUserName() + " 职称聘任" + positional.getPositionalType() + "导入成功");
                }
                else if (isUpdateSupport)
                {
                    positional.setPositionalId(p.getPositionalId());
                    positional.setUpdateBy(operName);
                    this.updateBasicPositional(positional);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、员工 " + positional.getUserName() + " 职称聘任" + positional.getPositionalType() + "更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、员工 " + positional.getUserName() + " 职称聘任" + positional.getPositionalType() + "已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、员工 " + positional.getUserName() + " 职称聘任导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 检查职称聘任等级唯一性
     * @param basicPositional
     * @return
     */
    @Override
    public String checkPositionalUnique(BasicPositional basicPositional) {
        Long positionalId = StringUtils.isNull(basicPositional.getPositionalId()) ? -1L : basicPositional.getPositionalId();
        BasicPositional info = baseMapper.selectOne(new LambdaQueryWrapper<BasicPositional>()
                .eq(BasicPositional::getPositionalType, basicPositional.getPositionalType())
                .eq(BasicPositional::getUserId, basicPositional.getUserId()).last("limit 1"));
        if (StringUtils.isNotNull(info) && info.getPositionalId().longValue() != positionalId.longValue())
        {
            return BasicConstants.POSITIONAL_TYPE_NOT_UNIQUE;
        }
        return BasicConstants.POSITIONAL_TYPE_UNIQUE;
    }
}
